//
//  LyricLineView.swift
//  每一行歌词View
//
//  Created by smile on 2019/4/20.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class LyricLineView: UIView {
    
    /**
     当前歌词行是否选中，也就是唱到这一行了
     */
    var isSelected=false
    
    
    /**
     是否是精确到字歌词
     */
    var isAccurate = false
    
    
    /**
     这一行歌词信息
     */
    var data:LyricLine?
    
    /**
     已经播放过的宽度
     */
    var playedLyricWidth:CGFloat = -1
    

    /**
     时间
     */
    var time:Float = 0

    /// 绘制
    /// 相当于Android中的View的onDraw
    ///
    /// - Parameter rect: <#rect description#>
    override func draw(_ rect: CGRect) {
        //如果没有歌词就返回
        if data==nil {
            return
        }
        
        //获取系统字体
        let font=UIFont.systemFont(ofSize: 18)
        
        //设置字体大小
        var attributes = [NSAttributedString.Key.font:font] as [NSAttributedString.Key:Any]
        
        let wordString = data!.data
        
        //获取歌词宽高
        let wordStringNSString=wordString! as NSString
        
        let size=computerSize(wordString!,attributes)

        //当前这行歌词绘制开始点
        //字的左上角
        let x=(self.frame.size.width-size.width)/2
        let y=(self.frame.size.height-size.height)/2
        let point=CGPoint(x: x, y: y)

        //获取图形绘制上下文
        let context=UIGraphicsGetCurrentContext()!
        
        //保存上下文
        //类似Android中View中在onDraw方法保存画图板状态
        context.saveGState()
        
        if isAccurate {
            //精确到字歌词
            //创建歌词的frame
            //大小正好和歌词宽高一样
            //同时左侧和point一样
            
            let frame=CGRect(x: point.x, y: point.y, width: size.width, height: size.height)
            
            //裁剪一个矩形区域
            context.clip(to: frame)
            
            //设置绘制颜色
            attributes[NSAttributedString.Key.foregroundColor]=UIColor.lightGray
            

            //绘制背景文字
            wordStringNSString.draw(at: point, withAttributes: attributes)
            
            if isSelected {
                //绘制高亮颜色
                                //获取当前时间点，是该行第几个字
                let lyricCurrentWordIndex=LyricUtil.getWordIndex(data!,time)
                if lyricCurrentWordIndex == -1 {
                    //当前行已经播放完成了
                    //所以播放的宽度就是当前行歌词宽度
                    playedLyricWidth=size.width
                }else{
                    //当前行没有播放完
                    //所以要计算播放时间
                    //获取当前字，已经唱过时间
                    let wordPlayedTime=LyricUtil.getWordPlayedTime(data!,time)
                    
                    //获取当前时间前面的文字
                    let beforeText=data!.data.substring(toIndex: lyricCurrentWordIndex)
                    
                    //前面的文字宽度
                    let beforeTextSize=computerSize(beforeText, attributes)
                    
                    //当前字
                    let currentWord=data!.words![lyricCurrentWordIndex]
                    
                    //当前字宽度
                    
                    //可以能大家觉得
                    //字宽度都是一定的
                    //但要考虑英文，所以要算
                    let currentWordSize=computerSize(currentWord, attributes)
                    
                    
                    //当前字已经播放的宽度

                    //计算方法：
                    //例如：当前字宽度为100px
                    //当前字持续时间为50
                    //那么 1px宽度=当前字宽度/当前字持续时间
                    //已经播放的宽度=1px宽度*已经播放的时间

                    //当前字持续时间
                    let currentWordDuration=data!.wordDurations![lyricCurrentWordIndex]
                    
                    let currentWordWidth=currentWordSize.width/CGFloat(currentWordDuration)*CGFloat(wordPlayedTime)
                   
                    //当前行已经播放的宽度
                    playedLyricWidth=beforeTextSize.width+currentWordWidth
                    
                    print("LyricLineView draw:\(beforeText),\(beforeTextSize.width),\(wordPlayedTime),\(currentWordWidth),\(playedLyricWidth)")
                    
                }
                
                
                //选中的矩形
                var selectedRect=frame
                selectedRect.size.width=self.playedLyricWidth
                
                //绘制高亮
                
                //裁剪矩形
                context.clip(to: selectedRect)
                
                //设置颜色为选中颜色
                attributes[NSAttributedString.Key.foregroundColor]=UIColor(hex: COLOR_PRIMARY)
                
                //绘制文本
                wordStringNSString.draw(at: point, withAttributes: attributes)
            }
        } else {
            //精确到行歌词
            //不用裁剪矩形，直接绘制
            
            if isSelected {
                //选中颜色
                attributes[NSAttributedString.Key.foregroundColor]=UIColor(hex: COLOR_PRIMARY)
            } else {
                //默认颜色
                attributes[NSAttributedString.Key.foregroundColor]=UIColor.lightGray
            }
            
            //绘制文本
            wordStringNSString.draw(at: point, withAttributes: attributes)
        }
        
        //恢复绘制的上下文
        context.restoreGState()
    }

    /// 计算NSString尺寸
    ///
    /// - Parameters:
    ///   - data: <#data description#>
    ///   - attributes: <#attributes description#>
    /// - Returns: <#return value description#>
    func computerSize(_ data:String,_ attributes:[NSAttributedString.Key:Any]) -> CGSize {
        
        //获取选项
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        
        //获取字符串的frame
        let rect:CGRect = data.boundingRect(with:self.frame.size, options: option, attributes: attributes, context: nil)
        
        //创建Size返回
        return CGSize(width: rect.width, height: rect.height)
    }
    
    //当前播放时间点
    //在这里要计算当前这一行，已经播放的时间
    func show(_ time:Float) {
        self.time=time
    }

}
